import Config from './config.js'
import JSEncrypt from 'jsencrypt'
import Util from './util.js'
import wx from './wx-jssdk.js'
// #ifdef H5
const app_type = Util.isWeiXin() ? 'wechat' : 'h5';
const app_type_name = Util.isWeiXin() ? '微信公众号' : 'H5';
// #endif

// #ifdef MP-WEIXIN
const app_type = 'weapp';
const app_type_name = '微信小程序';
// #endif

// #ifdef MP-ALIPAY
const app_type = 'aliapp';
const app_type_name = '支付宝小程序';
// #endif

// #ifdef MP-BAIDU
const app_type = 'baiduapp';
const app_type_name = '百度小程序';
// #endif

// #ifdef MP-TOUTIAO
const app_type = 'MP-TOUTIAO';
const app_type_name = '头条小程序';
// #endif

// #ifdef MP-QQ
const app_type = 'MP-QQ';
const app_type_name = 'QQ小程序';
// #endif

// #ifdef APP-PLUS
const app_type = 'app';
const app_type_name = 'APP';
// #endif
export default function(url, params, requestHeader) {
	let data = {
		app_type,
		app_type_name,
		...params
	}
	// 请求参数加密
	if (Config.apiSecurity) {
		let jsencrypt = new JSEncrypt();
		jsencrypt.setPublicKey(Config.publicKey);
		let encrypt = encodeURIComponent(jsencrypt.encryptLong(JSON.stringify(data)));
		data = {
			encrypt,
			app_type,
			app_type_name
		};
	}
	let token = uni.getStorageSync('token');
	let qmtoken = uni.getStorageSync('qmtoken');
	let tag = uni.getStorageSync('shoptag');
	if (token) {
		data.token = token;
	}
	if (qmtoken) {
		data.qm_token = qmtoken;
	}
	if (tag) {
		data.tag = tag;
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: Config.baseUrl + url,
			method: params ? 'POST' : 'GET',
			data: data,
			header: {
				'content-type': 'application/x-www-form-urlencoded;application/json'
			},
			dataType: 'json',
			responseType: 'text',
			success: (res) => {
				// console.log('APIrequest=>' + JSON.stringify(res.data));
				if (res.data.code == -999 && res.data.error_code == 'TOKEN_ERROR') {
					uni.removeStorageSync('token');
					uni.removeStorageSync('shoptag');
					uni.removeStorageSync('qmtoken');
					uni.removeStorageSync('authInfo');
					uni.removeStorageSync('userInfo');
				}
				if (res.data.code == -998 && (uni.getStorageSync('token') || uni.getStorageSync('qmtoken'))) {
					console.log('APItokenDelete=>' + uni.getStorageSync('token'));
					uni.removeStorageSync('token');
					uni.removeStorageSync('shoptag');
					uni.removeStorageSync('qmtoken');
					uni.removeStorageSync('authInfo');
					uni.removeStorageSync('userInfo');
					// let hash = location.hash;
					// if (hash.indexOf('?') > -1) {
					// 	hash = hash.substring(0, hash.indexOf('?'));
					// }
					// location.href = location.origin + '/' + hash;
					location.reload();
				}
				resolve(res);
			},
			fail: (res) => {
				reject(res);
			},
			complete: (res) => {
				reject(res);
			}
		});
	});
}
